<template>
 <div class="setting-page bfc">
   <div class="setting-form">
     <t-form ref="form" :data="formData" :rules="rules" @reset="onReset" @submit="onSubmit">
       <t-form-item
           label="初始密码"
           name="password"
           help="请输入初始的密码，默认为学工号。"
       >
         <t-input v-model="formData.password" type="password"></t-input>
       </t-form-item>
       <t-form-item label="修改密码" name="rePassword" help="请输入要更改的密码">
         <t-input v-model="formData.rePassword" type="password"></t-input>
       </t-form-item>
       <t-form-item style="padding-top: 8px">
         <t-button theme="primary" type="submit" style="margin-right: 10px">提交</t-button>
         <t-button theme="default" variant="base" type="reset">重置</t-button>
       </t-form-item>
     </t-form>
   </div>
 </div>
</template>
<script setup lang="ts">
import { ref } from 'vue';
import { changePassword } from "@/api";
import { MessagePlugin } from 'tdesign-vue-next';

const INITIAL_DATA = {
  password: '',
  rePassword: '',
};

const formData = ref({ ...INITIAL_DATA });
const form = ref(null);

const onReset = () => {
  MessagePlugin.success('重置成功');
};

const onSubmit = () => {
  if(!formData.value.password){
    return;
  }
  if(formData.value.password !== formData.value.rePassword){
    MessagePlugin.error('两次密码不一致哦！');
    return;
  }
  let u = JSON.parse(<string>sessionStorage.getItem("userInfo"));
  changePassword(u._id, formData.value.rePassword).then(res=>{
    if(res.data.code === 1){
      MessagePlugin.success(res.data.msg);
    } else {
      MessagePlugin.error(res.data.msg);
    }
  })
};


const rules = {
  password: [{ required: true, message: '密码必填', type: 'error' }],
  rePassword: [
    // 自定义校验规则
    { required: true, message: '密码必填', type: 'error' },
  ],
};
</script>

<style scoped>
.setting-form{
  width: 600px;
  padding: 50px;
  margin: 20px auto;
  box-shadow: 0 0 5px #ccc;
}
</style>
